#import "KFReportVC.h"
#import "BeanSelectionViewController.h"
#import "WSDatePickerView.h"
#import "KFReportCell.h" // 导入自定义cell

@interface KFReportVC ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSArray *beanData; // 豆子数据
@property (nonatomic, strong) NSMutableArray *selectedBeans; // 选中的豆子
@property (nonatomic, strong) UIButton *beanSelectButton; // 豆子选择按钮
@property (nonatomic, strong) UIButton *startDateButton; // 开始日期按钮
@property (nonatomic, strong) UIButton *endDateButton; // 结束日期按钮
@property (nonatomic, strong) NSDate *startDate; // 开始日期
@property (nonatomic, strong) NSDate *endDate; // 结束日期
@property (nonatomic, strong) UIView *selectedBeansContainer; // 选中的豆子容器
@property (nonatomic, strong) NSMutableDictionary *requestParams;
@property (nonatomic, strong) UIButton *queryButton;
@property (nonatomic, strong) UIButton *resetButton;
@property(nonatomic, strong) UITableView *myTab;

@end

@implementation KFReportVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTitle = @"报表";
    self.dataArr = [NSMutableArray new];
    self.selectedBeans = [NSMutableArray array];
    self.startDate = [NSDate date];
    self.endDate = [NSDate date];
    [self createUI];
    [self updateRequestParams];
    [self getBeans];
    
}
- (NSMutableDictionary *)requestParams {
    if (!_requestParams) {
        _requestParams = [NSMutableDictionary dictionary];
    }
    return _requestParams;
}
- (void)updateRequestParams {
    // 更新开始时间
    [self.requestParams removeAllObjects];
       
    // 更新开始时间（必传）
   if (self.startDate) {
       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
       formatter.dateFormat = @"yyyy-MM-dd 00:00:00";
       NSString *startTime = [formatter stringFromDate:self.startDate];
       [self.requestParams setObject:startTime forKey:@"startTime"];
   }
   
   // 更新结束时间（必传）
   if (self.endDate) {
       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
       formatter.dateFormat = @"yyyy-MM-dd 23:59:59";
       NSString *endTime = [formatter stringFromDate:self.endDate];
       [self.requestParams setObject:endTime forKey:@"endTime"];
   }
   
   // 更新豆子参数（可选）
   if (self.selectedBeans.count > 0) {
       NSMutableArray *beanValues = [NSMutableArray array];
       for (NSDictionary *bean in self.selectedBeans) {
           [beanValues addObject:bean[@"beanValue"]];
       }
       NSString *beanParam = [beanValues componentsJoinedByString:@","];
       [self.requestParams setObject:beanParam forKey:@"bean"];
   }
   
    
}
- (void)createUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 选中的豆子容器
    _selectedBeansContainer = [[UIView alloc] init];
    _selectedBeansContainer.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_selectedBeansContainer];
    
    // 豆子选择按钮
    _beanSelectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _beanSelectButton.backgroundColor = [UIColor systemBlueColor];
    [_beanSelectButton setTitle:@"请选择" forState:UIControlStateNormal];
    [_beanSelectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _beanSelectButton.titleLabel.font = [UIFont systemFontOfSize:14];
    _beanSelectButton.layer.cornerRadius = 4;
    [_beanSelectButton addTarget:self action:@selector(showBeanSelection) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_beanSelectButton];
    
    // 日期选择标题
    UILabel *dateTitleLabel = [[UILabel alloc] init];
    dateTitleLabel.text = @"选择日期";
    dateTitleLabel.font = [UIFont systemFontOfSize:15];
    dateTitleLabel.textColor = [UIColor darkTextColor];
    [self.view addSubview:dateTitleLabel];
    
    // 开始日期按钮
    _startDateButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _startDateButton.backgroundColor = [UIColor systemGray5Color];
    [_startDateButton setTitle:@"开始日期" forState:UIControlStateNormal];
    [_startDateButton setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
    _startDateButton.titleLabel.font = [UIFont systemFontOfSize:14];
    _startDateButton.layer.cornerRadius = 4;
    [_startDateButton addTarget:self action:@selector(showStartDatePicker) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_startDateButton];
    
    // 横杠标签
    UILabel *dashLabel = [[UILabel alloc] init];
    dashLabel.text = @"-";
    dashLabel.textAlignment = NSTextAlignmentCenter;
    dashLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:dashLabel];
    
    // 结束日期按钮
    _endDateButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _endDateButton.backgroundColor = [UIColor systemGray5Color];
    [_endDateButton setTitle:@"结束日期" forState:UIControlStateNormal];
    [_endDateButton setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
    _endDateButton.titleLabel.font = [UIFont systemFontOfSize:14];
    _endDateButton.layer.cornerRadius = 4;
    [_endDateButton addTarget:self action:@selector(showEndDatePicker) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_endDateButton];
    
    // 使用SDAutoLayout布局
    _selectedBeansContainer.sd_layout
    .topSpaceToView(self.view, 100)
    .leftSpaceToView(self.view, 20)
    .rightSpaceToView(self.view, 100) // 给选择按钮留出空间
    .minHeightIs(30);
    
    _beanSelectButton.sd_layout
    .topEqualToView(_selectedBeansContainer) // 顶部对齐而不是居中
    .rightSpaceToView(self.view, 20)
    .widthIs(80)
    .heightIs(30);
    
    dateTitleLabel.sd_layout
    .topSpaceToView(_selectedBeansContainer, 20)
    .leftSpaceToView(self.view, 20)
    .widthIs(80)
    .heightIs(20);
    
    _startDateButton.sd_layout
    .topSpaceToView(_selectedBeansContainer, 15)
    .leftSpaceToView(dateTitleLabel, 10)
    .widthIs(120)
    .heightIs(36);
    
    dashLabel.sd_layout
    .centerYEqualToView(_startDateButton)
    .leftSpaceToView(_startDateButton, 10)
    .widthIs(20)
    .heightIs(36);
    
    _endDateButton.sd_layout
    .centerYEqualToView(_startDateButton)
    .leftSpaceToView(dashLabel, 10)
    .widthIs(120)
    .heightIs(36);
    _queryButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _queryButton.backgroundColor = [UIColor systemGreenColor];
        [_queryButton setTitle:@"查询" forState:UIControlStateNormal];
        [_queryButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _queryButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _queryButton.layer.cornerRadius = 4;
        [_queryButton addTarget:self action:@selector(queryData) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_queryButton];
    
    _resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _resetButton.backgroundColor = [UIColor systemOrangeColor];
        [_resetButton setTitle:@"重置" forState:UIControlStateNormal];
        [_resetButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _resetButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _resetButton.layer.cornerRadius = 4;
        [_resetButton addTarget:self action:@selector(resetData) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_resetButton];
    // 表格
       [self.view addSubview:self.myTab];
       
       // 使用SDAutoLayout布局
       _selectedBeansContainer.sd_layout
       .topSpaceToView(self.view, 100)
       .leftSpaceToView(self.view, 20)
       .rightSpaceToView(self.view, 100)
       .minHeightIs(30);
       
       _beanSelectButton.sd_layout
       .topEqualToView(_selectedBeansContainer)
       .rightSpaceToView(self.view, 20)
       .widthIs(80)
       .heightIs(30);
       
       dateTitleLabel.sd_layout
       .topSpaceToView(_selectedBeansContainer, 20)
       .leftSpaceToView(self.view, 20)
       .widthIs(80)
       .heightIs(20);
       
       _startDateButton.sd_layout
       .topSpaceToView(_selectedBeansContainer, 15)
       .leftSpaceToView(dateTitleLabel, 10)
       .widthIs(120)
       .heightIs(36);
       
       dashLabel.sd_layout
       .centerYEqualToView(_startDateButton)
       .leftSpaceToView(_startDateButton, 10)
       .widthIs(20)
       .heightIs(36);
       
       _endDateButton.sd_layout
       .centerYEqualToView(_startDateButton)
       .leftSpaceToView(dashLabel, 10)
       .widthIs(120)
       .heightIs(36);
       
       _queryButton.sd_layout
       .centerYEqualToView(_startDateButton)
       .rightSpaceToView(self.view, 90)
       .widthIs(60)
       .heightIs(36);
       
       _resetButton.sd_layout
       .centerYEqualToView(_startDateButton)
       .rightSpaceToView(self.view, 20)
       .widthIs(60)
       .heightIs(36);
       
       _myTab.sd_layout
       .topSpaceToView(_startDateButton, 20)
       .leftSpaceToView(self.view, 0)
       .rightSpaceToView(self.view, 0)
       .bottomSpaceToView(self.view, 0);
       
       [self updateDateButtons];
       [self updateSelectedBeansDisplay];
}
#pragma mark - 更新日期按钮显示
- (void)updateDateButtons {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
       formatter.dateFormat = @"yyyy-MM-dd";
       
       if (self.startDate) {
           NSString *startDateStr = [formatter stringFromDate:self.startDate];
           [self.startDateButton setTitle:startDateStr forState:UIControlStateNormal];
       } else {
           [self.startDateButton setTitle:@"开始日期" forState:UIControlStateNormal];
       }
       
       if (self.endDate) {
           NSString *endDateStr = [formatter stringFromDate:self.endDate];
           [self.endDateButton setTitle:endDateStr forState:UIControlStateNormal];
       } else {
           [self.endDateButton setTitle:@"结束日期" forState:UIControlStateNormal];
       }
}
#pragma mark - 重置按钮点击事件
- (void)resetData {
    // 重置日期为当天
    self.startDate = [NSDate date];
    self.endDate = [NSDate date];
    [self updateDateButtons];
    
    // 清空选中的豆子
    [self.selectedBeans removeAllObjects];
    [self updateSelectedBeansDisplay];
    
    // 更新参数
    [self updateRequestParams];
    [self getData];
}
#pragma mark - 查询按钮点击事件
- (void)queryData {
    if (!self.startDate) {
        XHQHUDErrorText(@"请选择开始日期");
        return;
    }
    if (!self.endDate) {
        XHQHUDErrorText(@"请选择结束日期");
        return;
    }
    if ([self.endDate compare:self.startDate] == NSOrderedAscending) {
        XHQHUDErrorText(@"结束日期不能早于开始日期");
        return;
    }
    [self updateRequestParams];
    [self getData];
}
#pragma mark - 更新选中的豆子显示
- (void)updateSelectedBeansDisplay {
    // 清除容器中的所有子视图
    [_selectedBeansContainer.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    if (self.selectedBeans.count == 0) {
        // 如果没有选中任何豆子，显示提示文本
        UILabel *hintLabel = [[UILabel alloc] init];
        hintLabel.text = @"请选择豆子";
        hintLabel.textColor = [UIColor lightGrayColor];
        hintLabel.font = [UIFont systemFontOfSize:14];
        [_selectedBeansContainer addSubview:hintLabel];
        
        hintLabel.sd_layout
        .leftSpaceToView(_selectedBeansContainer, 0)
        .centerYEqualToView(_selectedBeansContainer)
        .heightIs(20);
        [hintLabel setSingleLineAutoResizeWithMaxWidth:200];
        
        // 更新容器高度
        _selectedBeansContainer.sd_layout.heightIs(30);
        
    } else {
        // 创建豆子标签
        CGFloat currentX = 0;
        CGFloat currentY = 0;
        CGFloat maxWidth = CGRectGetWidth(self.view.frame) - 120; // 减去选择按钮的宽度和边距
        CGFloat tagHeight = 25;
        CGFloat horizontalSpacing = 8;
        CGFloat verticalSpacing = 8;
        
        for (int i = 0; i < self.selectedBeans.count; i++) {
            NSDictionary *bean = self.selectedBeans[i];
            NSString *beanName = bean[@"beanName"];
            
            // 创建豆子标签容器
            UIView *beanTagView = [[UIView alloc] init];
            beanTagView.backgroundColor = [UIColor clearColor];
            beanTagView.layer.borderWidth = 1.0;
            beanTagView.layer.borderColor = [UIColor systemBlueColor].CGColor;
            beanTagView.layer.cornerRadius = 4;
            beanTagView.tag = i; // 使用索引作为tag
            [_selectedBeansContainer addSubview:beanTagView];
            
            // 豆子名称标签
            UILabel *beanLabel = [[UILabel alloc] init];
            beanLabel.text = beanName;
            beanLabel.font = [UIFont systemFontOfSize:12];
            beanLabel.textColor = [UIColor darkTextColor];
            [beanTagView addSubview:beanLabel];
            
            // 关闭按钮
            UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [closeButton setTitle:@"×" forState:UIControlStateNormal];
            [closeButton setTitleColor:[UIColor systemRedColor] forState:UIControlStateNormal];
            closeButton.titleLabel.font = [UIFont systemFontOfSize:16];
            closeButton.tag = i; // 使用索引作为tag
            [closeButton addTarget:self action:@selector(removeBean:) forControlEvents:UIControlEventTouchUpInside];
            [beanTagView addSubview:closeButton];
            
            // 计算标签宽度（名称宽度 + 关闭按钮宽度）
            CGFloat nameWidth = [beanName boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, tagHeight)
                                                      options:NSStringDrawingUsesLineFragmentOrigin
                                                   attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}
                                                      context:nil].size.width;
            CGFloat tagWidth = nameWidth + 25; // 名称宽度 + 关闭按钮区域
            
            // 检查是否需要换行
            if (currentX + tagWidth > maxWidth) {
                currentX = 0;
                currentY += tagHeight + verticalSpacing;
            }
            
            // 设置容器布局
            beanTagView.sd_layout
            .leftSpaceToView(_selectedBeansContainer, currentX)
            .topSpaceToView(_selectedBeansContainer, currentY)
            .widthIs(tagWidth)
            .heightIs(tagHeight);
            
            // 设置名称标签布局
            beanLabel.sd_layout
            .leftSpaceToView(beanTagView, 5)
            .centerYEqualToView(beanTagView)
            .heightIs(tagHeight);
            [beanLabel setSingleLineAutoResizeWithMaxWidth:nameWidth];
            
            // 设置关闭按钮布局
            closeButton.sd_layout
            .rightSpaceToView(beanTagView, 2)
            .centerYEqualToView(beanTagView)
            .widthIs(20)
            .heightIs(tagHeight);
            
            currentX += tagWidth + horizontalSpacing;
        }
        
        // 更新容器高度
        CGFloat containerHeight = currentY + tagHeight;
        _selectedBeansContainer.sd_layout.heightIs(containerHeight);
    }
    
    // 更新布局
    [_selectedBeansContainer updateLayout];
}
#pragma mark - 删除豆子
- (void)removeBean:(UIButton *)sender {
    NSInteger index = sender.tag;
    
    if (index < self.selectedBeans.count) {
        // 从选中数组中移除
        [self.selectedBeans removeObjectAtIndex:index];
        
        // 更新显示
        [self updateSelectedBeansDisplay];
        
        // 更新参数（但不发送请求）
        [self updateRequestParams];
        
    }
}
#pragma mark - 豆子选择
- (void)showBeanSelection {
    BeanSelectionViewController *beanVC = [[BeanSelectionViewController alloc] init];
    beanVC.selectedBeans = [self.selectedBeans mutableCopy];
    
    __weak typeof(self) weakSelf = self;
    beanVC.completion = ^(NSArray *selectedBeans) {
        weakSelf.selectedBeans = [selectedBeans mutableCopy];
        [weakSelf updateSelectedBeansDisplay];
        // 只更新参数，不发送请求
        [weakSelf updateRequestParams];
    };
    
    beanVC.modalPresentationStyle = UIModalPresentationPageSheet;
    if (@available(iOS 15.0, *)) {
        UISheetPresentationController *sheet = beanVC.sheetPresentationController;
        if (sheet) {
            sheet.detents = @[UISheetPresentationControllerDetent.mediumDetent, UISheetPresentationControllerDetent.largeDetent];
            sheet.prefersGrabberVisible = YES;
        }
    }
    
    [self presentViewController:beanVC animated:YES completion:nil];
}

- (void)sendBeanDataToServer {
    [self updateRequestParams];
    [self getData];
}

#pragma mark - 日期选择回调修改（移除自动请求）
- (void)showStartDatePicker {
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
        NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
        [self.startDateButton setTitle:date forState:UIControlStateNormal];
        self.startDate = selectDate;
        // 只更新参数，不发送请求
        [self updateRequestParams];
        NSLog(@"选择的开始日期：%@", date);
    }];
    [datepicker show];
}

- (void)showEndDatePicker {
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
        NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
        [self.endDateButton setTitle:date forState:UIControlStateNormal];
        self.endDate = selectDate;
        // 只更新参数，不发送请求
        [self updateRequestParams];
        NSLog(@"选择的结束日期：%@", date);
    }];
    [datepicker show];
}

-(void)getBeans{
    NSString * url = [WorkUrl returnURL:Interface_For_Get_Beans_Data];
    [PGNetworkHelper GET:url parameters:nil cache:NO headers:[Mytools getHeaders] responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            VicSingleObject * single = [VicSingleObject getInstance];
            single.beansList = responseObject[@"data"];
            self.beanData = responseObject[@"data"];
            [self updateSelectedBeansDisplay];
            [self getData];
        }else{
            XHQHUDErrorText(responseObject[@"message"]);
        }
    } failure:^(id error) {
        XHQHUDErrorText(error[@"msg"]);
    }];
}

-(void)getData{
    NSString * url = [WorkUrl returnURL:Interface_For_Get_Report_List];
    [PGNetworkHelper GET:url parameters:self.requestParams cache:NO headers:[Mytools getHeaders] responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            // 清空原有数据
            [self.dataArr removeAllObjects];
            
            // 添加新数据
            NSArray *dataArray = responseObject[@"data"];
            if ([dataArray isKindOfClass:[NSArray class]]) {
                [self.dataArr addObjectsFromArray:dataArray];
            }
            
            // 刷新表格
            [self.myTab reloadData];
            
            // 结束刷新
            if ([self.myTab.mj_header isRefreshing]) {
                [self.myTab.mj_header endRefreshing];
            }
        } else {
            XHQHUDErrorText(responseObject[@"message"]);
        }
    } failure:^(id error) {
        XHQHUDErrorText(error[@"msg"]);
        // 结束刷新
        if ([self.myTab.mj_header isRefreshing]) {
            [self.myTab.mj_header endRefreshing];
        }
    }];
}
#pragma mark 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"KFReportCell";
    KFReportCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[KFReportCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    // 配置cell数据
    if (indexPath.row < self.dataArr.count) {
        NSDictionary *data = self.dataArr[indexPath.row];
        [cell configureWithData:data];
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableView *)myTab {
    if (!_myTab) {
        _myTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTab.dataSource = self;
        _myTab.delegate = self;
        _myTab.backgroundColor = UnderLineColor;
        __weak typeof(self)weakSelf = self;
        [_myTab registerClass:[KFReportCell class] forCellReuseIdentifier:@"KFReportCell"];

        _myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf.dataArr removeAllObjects];
            [weakSelf getData];
        }];
    }
    return _myTab;
}


@end
